<template>
  <div class="success-page">
    <div class="container">
      <!-- 返回按钮 -->
      <button class="back-btn" @click="convertNew">
        ← 返回
      </button>

      <!-- 标题区域 -->
      <div class="page-header">
        <h1 class="page-title">抠图结果</h1>
      </div>

      <!-- 主内容卡片 -->
      <div class="content-card">
        <!-- 对比预览区域 -->
        <div class="preview-container">
          <!-- 原图预览 -->
          <div class="preview-box">
            <h3 class="preview-title">原图</h3>
            <div class="image-wrapper">
              <img v-if="mattingData.originalFileUrl" 
                :src="mattingData.originalFileUrl" 
                alt="原始图片" 
                class="preview-image"
                @error="handleImageError" 
              />
            </div>
          </div>

          <!-- 抠图结果 -->
          <div class="preview-box">
            <h3 class="preview-title">抠图结果</h3>
            <div class="image-wrapper checkered-bg">
              <img :src="mattingDataWithTimestamp" 
                alt="抠图结果" 
                class="preview-image" 
                @error="handleImageError" 
              />
            </div>
          </div>
        </div>

        <!-- 操作按钮组 -->
        <div class="action-buttons">
          <button class="action-btn manual-matting-btn" @click="openManualEditor">
            手动抠图
          </button>
          <button class="action-btn download-btn" @click="downloadImage">
            下载透明PNG
          </button>
        </div>

        <!-- 文件信息列表 -->
        <div class="info-list">
          <div class="info-row">
            <span class="info-label">原始尺寸:</span>
            <span class="info-value">{{ mattingData.originalWidth }} × {{ mattingData.originalHeight }}px</span>
          </div>
          <div class="info-row">
            <span class="info-label">输出尺寸:</span>
            <span class="info-value">{{ mattingData.outputWidth }} × {{ mattingData.outputHeight }}px</span>
          </div>
          <div class="info-row">
            <span class="info-label">原始大小:</span>
            <span class="info-value">{{ formatFileSize(mattingData.originalFileSize) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">输出大小:</span>
            <span class="info-value">{{ formatFileSize(mattingData.outputFileSize) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">抠图算法:</span>
            <span class="info-value">{{ getAlgorithmName(mattingData.mattingAlgorithm) }}</span>
          </div>
        </div>
      </div>

      <!-- 成功提示 -->
      <div class="success-message">
        <span class="success-icon">✓</span>
        <div class="success-text">
          <strong>抠图完成！</strong>
          <p>您的图片已经成功抠图，背景已移除，可以预览、下载或分享。如需进一步优化，可使用"手动抠图"功能。</p>
        </div>
      </div>
    </div>

    <!-- 手动编辑器 -->
    <ManualMattingEditor 
      :visible="showManualEditor"
      :imageUrl="mattingData.downloadUrl"
      :originalImageUrl="mattingData.originalFileUrl"
      @close="closeManualEditor"
      @confirm="confirmManualEdit"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { toastSuccess, toastError, toastInfo } from '@/utils/toast'
import ManualMattingEditor from '@/components/ManualMattingEditor.vue'
import { uploadManualMattingResult } from '@/api/conversion'

const router = useRouter()
const mattingData = ref({
  downloadUrl: '',
  outputFilename: '',
  originalFilename: '',
  originalFileUrl: '',
  outputFileSize: 0,
  originalFileSize: 0,
  outputWidth: 0,
  outputHeight: 0,
  originalWidth: 0,
  originalHeight: 0,
  mattingAlgorithm: '',
  id: null
})

// 手动编辑器状态
const showManualEditor = ref(false)

// 添加时间戳参数防止浏览器缓存
const mattingDataWithTimestamp = computed(() => {
  if (!mattingData.value.downloadUrl) return ''
  const separator = mattingData.value.downloadUrl.includes('?') ? '&' : '?'
  return `${mattingData.value.downloadUrl}${separator}t=${Date.now()}`
})

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  toastError('图片加载失败，请刷新页面重试')
}

onMounted(() => {
  // 从sessionStorage获取转换结果数据
  const resultData = sessionStorage.getItem('mattingResult')
  if (resultData) {
    const data = JSON.parse(resultData)
    mattingData.value = data
    console.log('抠图结果数据:', data)
  } else {
    // 如果没有数据，跳转回抠图页面
    router.push('/image-matting')
  }
})

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'
  if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
  return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
}

// 获取算法名称
const getAlgorithmName = (algorithm) => {
  const names = {
    'u2net': '通用抠图 (U2-Net)',
    'u2netp': '快速抠图 (U2-Net Lite)',
    'u2net_human_seg': '人物抠图',
    'u2net_cloth_seg': '服装抠图',
    'silueta': '高质量人像',
    'REMBG': '智能抠图'
  }
  return names[algorithm] || algorithm || '未知'
}

// 转换新图片
const convertNew = () => {
  // 清除sessionStorage中的数据
  sessionStorage.removeItem('mattingResult')
  // 跳转回抠图页面
  router.push('/image-matting')
}

// 打开手动编辑器
const openManualEditor = () => {
  if (!mattingData.value.downloadUrl) {
    toastError('无法打开编辑器，图片地址不存在')
    return
  }
  showManualEditor.value = true
}

// 关闭手动编辑器
const closeManualEditor = () => {
  showManualEditor.value = false
}

// 确认手动编辑结果 - 替换原记录
const confirmManualEdit = async (blob) => {
  try {
    // 显示加载提示
    toastInfo('正在保存手动抠图结果，请稍候...')
    
    // 构建 FormData
    const formData = new FormData()
    formData.append('file', blob, 'manual-matting.png')
    
    // 传递原始记录ID，用于更新而非创建新记录
    if (mattingData.value.id) {
      formData.append('recordId', mattingData.value.id)
      formData.append('replaceMode', 'true')  // 标记为替换模式
    }
    
    // 上传手动编辑的结果
    const response = await uploadManualMattingResult(formData)
    
    if (response.code === 200 && response.data) {
      // 更新当前显示的数据
      mattingData.value = {
        ...response.data,
        mattingAlgorithm: '手动抠图'
      }
      
      // 更新 sessionStorage
      sessionStorage.setItem('mattingResult', JSON.stringify(mattingData.value))
      
      toastSuccess('手动抠图结果已保存')
      showManualEditor.value = false
      
      // 使用数据更新代替页面刷新，添加时间戳强制重新加载图片
      // 这样比 window.location.reload() 快很多
      mattingData.value.downloadUrl = response.data.downloadUrl + '&_t=' + Date.now()
      mattingData.value.originalFileUrl = response.data.originalFileUrl + '&_t=' + Date.now()
    } else {
      throw new Error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存手动抠图结果失败:', error)
    toastError('保存失败: ' + (error.message || '请重试'))
  }
}

// 直接下载（不跳转页面）
const downloadImage = async () => {
  if (!mattingData.value.downloadUrl) {
    toastError('下载地址不存在')
    return
  }
  
  try {
    const downloadUrl = mattingData.value.downloadUrl
    const filename = mattingData.value.outputFilename || 'matting-result.png'
    
    // 判断是否为外部URL（COS URL）
    const isExternalUrl = downloadUrl.startsWith('http://') || downloadUrl.startsWith('https://')
    
    if (isExternalUrl && !downloadUrl.includes('/api/files/')) {
      // 对于COS URL，直接创建下载链接（避免CORS问题）
      const a = document.createElement('a')
      a.href = downloadUrl
      a.download = filename
      a.target = '_blank'
      document.body.appendChild(a)
      a.click()
      a.remove()
      toastSuccess('开始下载')
    } else {
      // 对于本地URL或代理URL，使用fetch下载
      const url = downloadUrl.includes('?') ? `${downloadUrl}&download=true` : `${downloadUrl}?download=true`
      const res = await fetch(url)
      if (!res.ok) {
        throw new Error('下载失败：' + res.statusText)
      }
      
      const blob = await res.blob()
      const blobUrl = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = blobUrl
      a.download = filename
      document.body.appendChild(a)
      a.click()
      URL.revokeObjectURL(blobUrl)
      a.remove()
      toastSuccess('下载成功')
    }
  } catch (error) {
    console.error('下载失败:', error)
    toastError('下载失败: ' + (error.message || '网络错误，稍后重试'))
  }
}
</script>

<style scoped>
.success-page {
  min-height: 100vh;
  width: 100vw;
  background: #f5f7fa;
  padding: 40px 20px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow-x: hidden;
}

.container {
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
}

/* 返回按钮 */
.back-btn {
  background: white;
  border: 1px solid #e5e7eb;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 0.95rem;
  color: #374151;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 20px;
  font-weight: 500;
}

.back-btn:hover {
  background: #f9fafb;
  border-color: #d1d5db;
}

/* 页面标题 */
.page-header {
  background: #e0e7ff;
  padding: 16px 24px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.page-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

/* 主内容卡片 */
.content-card {
  background: white;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 对比预览容器 */
.preview-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.preview-box {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.preview-title {
  font-size: 1rem;
  font-weight: 600;
  color: #4b5563;
  margin: 0;
  text-align: center;
}

.image-wrapper {
  background: #f9fafb;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  border: 1px solid #e5e7eb;
  overflow: hidden;
}

/* 棋盘格背景（用于显示透明效果） */
.checkered-bg {
  background-image: 
    linear-gradient(45deg, #e5e7eb 25%, transparent 25%),
    linear-gradient(-45deg, #e5e7eb 25%, transparent 25%),
    linear-gradient(45deg, transparent 75%, #e5e7eb 75%),
    linear-gradient(-45deg, transparent 75%, #e5e7eb 75%);
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
}

.preview-image {
  max-width: 100%;
  max-height: 400px;
  width: auto;
  height: auto;
  display: block;
  object-fit: contain;
  border-radius: 8px;
}

/* 操作按钮组 */
.action-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 24px;
}

.action-btn {
  padding: 16px;
  border-radius: 10px;
  font-size: 1.05rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.manual-matting-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.manual-matting-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.download-btn {
  background: #10b981;
  color: white;
}

.download-btn:hover {
  background: #059669;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

/* 信息列表 */
.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-row {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
  gap: 8px;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 0.95rem;
  color: #6b7280;
  font-weight: 500;
  min-width: 100px;
}

.info-value {
  font-size: 0.95rem;
  color: #111827;
  font-weight: 500;
}

/* 成功提示 */
.success-message {
  background: #d1fae5;
  border: 1px solid #a7f3d0;
  border-radius: 12px;
  padding: 20px 24px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.success-icon {
  width: 28px;
  height: 28px;
  background: #10b981;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  font-weight: bold;
  flex-shrink: 0;
}

.success-text {
  flex: 1;
}

.success-text strong {
  display: block;
  font-size: 1.05rem;
  color: #065f46;
  margin-bottom: 6px;
}

.success-text p {
  font-size: 0.9rem;
  color: #047857;
  margin: 0;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .success-page {
    padding: 16px;
  }

  .preview-container {
    grid-template-columns: 1fr;
  }

  .content-card {
    padding: 24px;
  }

  .image-wrapper {
    min-height: 250px;
    padding: 16px;
  }

  .page-title {
    font-size: 1.1rem;
  }

  .action-buttons {
    grid-template-columns: 1fr;
  }

  .action-btn {
    padding: 14px;
    font-size: 1rem;
  }

  .success-message {
    padding: 16px;
  }

  .info-label {
    min-width: 80px;
  }
}

@media (max-width: 480px) {
  .page-header {
    padding: 12px 16px;
  }

  .content-card {
    padding: 20px;
  }

  .info-label {
    font-size: 0.85rem;
  }

  .info-value {
    font-size: 0.85rem;
  }
}
</style>



